Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[revised, tests added] added support for buffer / memoryview data #147

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

peci1
Copy link

@peci1 peci1 commented Nov 25, 2022

I iterated on #108 to add support for direct serialization of buffer protocol objects.

Closes #107.

I've added as much tests as I could imagine.

The generated code is a bit ugly because I found that if you pass a string to uint8[] field, its length is not checked. I wanted to explicitly make sure this behavior is kept for strings, but it did not occur good to me to keep it for the buffer protocol objects.

One of the use-cases I have for this feature is incrementally building a PointCloud2. If you represent the data field as bytearray, you get all the nice std::vector<>-like behavior (amortized O(1) append). And if this bytearray can be directly used in serialization, then the only copy you need to make is the serialization itself. Currently, I need to call bytes(my_bytearray_data), which makes a copy, and then pass this copy to the serialization. So that's an unnecessary copy of a whole lot of data (in the case of pointclouds).


Struct.pack pads with zeros if a shorter string is given, or cuts the string it if is longer:

In[8]: struct.Struct('<4s').pack(b"asd")
Out[8]: 'asd\x00'

@peci1 peci1 force-pushed the fix-buffer branch 2 times, most recently from be3e1dd to ff15d30 Compare November 25, 2022 18:40
@peci1
Copy link
Author

peci1 commented Nov 25, 2022

There is probably also a bug in the tests themselves:

genpy.message.check_type('test', 'uint8[]', 'byteDataIsAStringInPy')
genpy.message.check_type('test', 'char[]', 'byteDataIsAStringInPy')

In Python3, strings cannot be packed by the s modifier of Struct.pack. So check_type should not succeed, but it does. The serialization then fails.

@peci1 peci1 marked this pull request as ready for review November 25, 2022 18:44
@peci1
Copy link
Author

peci1 commented Nov 25, 2022

According to https://peps.python.org/pep-0688/ , in Python < 3.12, there is really no better way to test buffer protocol support than the try/except...

Signed-off-by: Martin Pecka <peckama2@fel.cvut.cz>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

memoryview / buffer inputs should be accepted as serializable data
2 participants